using CefSharp;
using System.Windows.Forms;
using DidaManager.Log;
using CefSharp.WinForms;
using System.Threading;

namespace DidaManager
{
    internal static class Program
    {
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern bool SetProcessDPIAware();

        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // 启用高DPI支持以改善缩放质量
            //Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            // 添加互斥量，只允许启动一个进程
            bool createdNew;
            var singleInstanceMutex = new Mutex(true, "Global\\DidaManager_SingleInstance", out createdNew);
            if (!createdNew)
            {
                MessageBox.Show("DidaManager程序已在运行。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // ***this line is added***
            if (Environment.OSVersion.Version.Major >= 6)
                SetProcessDPIAware();

            CefSharpSettings.ConcurrentTaskExecution = true;
            try
            {
                // 初始化日志系统
                LogManager.Initialize();
                LogManager.Info("应用程序启动");

                string cachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache");
                if (!Directory.Exists(cachePath))
                {
                    Directory.CreateDirectory(cachePath);// 创建cache文件夹
                }
                // 确保 CefSharp 已初始化
                if (Cef.IsInitialized == false)
                {
                    var settings = new CefSettings();
                    // 最基本的设置
                    settings.CachePath = cachePath;

                    // 初始化 CefSharp
                    Cef.Initialize(settings);
                }
                
                LogManager.Info("创建主窗体");
                Application.Run(new MainForm());
                
                LogManager.Info("应用程序正常退出");
            }
            catch (Exception ex)
            {
                LogManager.Error("程序启动时出错", ex);
                MessageBox.Show($"程序启动时出错：{ex.Message}\n{ex.StackTrace}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                singleInstanceMutex?.ReleaseMutex();
                singleInstanceMutex?.Dispose();
            }
        }
    }
}